import 'package:fish_redux/fish_redux.dart';
import '../../../../app_files.dart';
import 'action.dart';
import 'state.dart';

Effect<SelectCommunityViewState> buildEffect() {
  return combineEffects(<Object, Effect<SelectCommunityViewState>>{
    SelectCommunityViewAction.onLoad: _onLoad,
    SelectCommunityViewAction.onSearch: _onSearch,
    SelectCommunityViewAction.onClearText: _onClearText,
    Lifecycle.initState: _initState,
  });
}


void _onClearText(Action action, Context<SelectCommunityViewState> ctx) async {
  ctx.state.textEditingController.text = '';
  ctx.state.showClose = false;
  ctx.dispatch(
      SelectCommunityViewActionCreator.onGetData({'items': null, 'page': 1}));
  await _sendRequest(ctx, 1);

}

void _initState(Action action, Context<SelectCommunityViewState> ctx) {
  _sendRequest(ctx, 1);
}

void _onSearch(Action action, Context<SelectCommunityViewState> ctx) async {
  ctx.dispatch(
      SelectCommunityViewActionCreator.onGetData({'items': null, 'page': 1}));
  await _sendRequest(ctx, 1);
}

void _onLoad(Action action, Context<SelectCommunityViewState> ctx) async {
  await _sendRequest(ctx, action.payload);
}

_sendRequest(Context<SelectCommunityViewState> ctx, int page) async {
  ResultData res = await CommonNetWork.getCommunityList(page,key: ctx.state.textEditingController.text);
  if (res.success) {
    List data = res.data;
    List<CommunityModel> items =
        data.map<CommunityModel>((e) => CommunityModel.fromJson(e)).toList();
    ctx.dispatch(SelectCommunityViewActionCreator.onGetData(
        {'items': items, 'page': page}));
  } else {
    await CommonUtils.showAlertView(ctx.context, res.desc);
    Navigator.pop(ctx.context);
  }
}
